﻿using CPPEI.App.Console;
using CPPEI.Coolzon.Common.Startup;
using CPPEI.Coolzon.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.BD.VideoMatrixTool
{
    /// <summary>
    /// 视频矩阵切换工具，向视频矩阵发送udp包以达到视频切换的工作
    /// <para>
    /// 发送到默认的地址和端口，地址和端口来自配置文件：app.config
    /// VideoMatrixTool.exe /solution s1
    /// </para>
    /// <para>
    /// 发送到指定的地址和端口
    /// VideoMatrixTool.exe /solution s1 /ip 127.0.0.1 /port 1111
    /// </para>
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            new VideoMatrixToolApp().Run(args);
        }
    }

    class VideoMatrixToolApp : XApplication
    {
        private string _solution;
        public VideoMatrixToolApp()
            : base("CPPEI", "BD", "VideoMatrixTool", "VideoMatrixTool")
        {
            Settings.IsAutoRun = false;
            Settings.IsSingleton = false;
        }

        protected override bool OnXStartup(StartupParamCollection startupParams)
        {
           
            _solution = startupParams.GetValue("solution");
             Console.WriteLine(string.Format("收到{0}指令,值为{1}","solution",_solution));
            if (string.IsNullOrEmpty(startupParams.GetValue("ip")) || string.IsNullOrEmpty(startupParams.GetValue("port")))
            {
               return SendDefaltTarget();
            }
            else
            {
               return SendPointTarget(startupParams.GetValue("ip"),startupParams.GetValue("port"));
            }
           
        }

        /// <summary>
        /// 发送到默认的地址和端口
        /// </summary>
        /// <returns></returns>
        private bool SendDefaltTarget()
        {
            string targetIp = ConfigurationManager.AppSettings["TargetIp"].ToString();
            string targetPort = ConfigurationManager.AppSettings["TargetPort"].ToString();
            if (!string.IsNullOrEmpty(targetIp) && !string.IsNullOrEmpty(targetPort))
            { 
                //XConfigUtil.Init(,GetSolutionFilePath());
                Console.WriteLine(string.Format("发送到默认的地址和端口：{0}:{1}", targetIp,targetPort));
                List<Datas.Solution> ListSolution = GetSolutionBySolutionName();
                if (ListSolution != null)
                {
                    foreach (Datas.Solution solution in ListSolution)
                    {
                        foreach(Datas.Mapping mapping in solution.Mapping)
                        {
                            string strUdp = string.Format("CDP_I{0}O{1}_T", mapping.VideoSourceId, mapping.VideoMatrixId);
                            byte[] udpData = System.Text.Encoding.Default.GetBytes(strUdp);
                            Console.WriteLine(string.Format("发送指令：{0}", strUdp));
                            SendUdpClient(targetIp, targetPort, udpData, udpData.Length);
                        }
                       
                    }
                }
                
            }

            return true;
        }



        /// <summary>
        /// 发送到制定地址和端口
        /// </summary>
        /// <returns></returns>
        private bool SendPointTarget(string ip, string port)
        {
            Console.WriteLine(string.Format("发送到默认的地址和端口：{0}:{1}", ip, port));
            List<Datas.Solution> ListSolution = GetSolutionBySolutionName();
            if (ListSolution != null)
            {
                foreach (Datas.Solution solution in ListSolution)
                {
                    foreach (Datas.Mapping mapping in solution.Mapping)
                    {
                        string strUdp = string.Format("CDP_I{0}O{1}_T", mapping.VideoSourceId, mapping.VideoMatrixId);
                        byte[] udpData = System.Text.Encoding.Default.GetBytes(strUdp);
                        Console.WriteLine(string.Format("发送指令:{0}", strUdp));
                        SendUdpClient(ip, port, udpData, udpData.Length);
                    }

                }
            }
            return true;
        }

        private bool SendUdpClient(string ip, string port,byte[] sendData,int bytes)
        {
            try
            {
                IPAddress hostIP = IPAddress.Parse(ip);
                IPEndPoint host = new IPEndPoint(hostIP, Convert.ToInt32(port));
                UdpClient udpClient = new UdpClient();

                udpClient.Send(sendData, bytes, host);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        /// <summary>
        /// 根据方案名获取方案对应的视频与矩阵信息
        /// </summary>
        /// <returns></returns>
        private List<Datas.Solution> GetSolutionBySolutionName()
        {
           return XSolutionConfigUntil.GetListSolutionByName(_solution, GetSolutionFilePath());
        }

        /// 获取solution.xml文件的地址
        /// </summary>
        /// <returns></returns>
        public static string GetSolutionFilePath()
        {
            return string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "solution.xml");
        }

       
    }
}
